package com.hooper.solution.day13;


import java.util.Arrays;
import java.util.Comparator;

/**
 * @author Tim Hooper
 * @version 1.0
 * @time 2023/02/28/15:30
 */
public class Solutions {

    /**
     * 14. 最长公共前缀
     * 编写一个函数来查找字符串数组中的最长公共前缀。
     * 如果不存在公共前缀，返回空字符串 ""。
     * 示例 1：
     * 输入：strs = ["flower","flow","flight"]
     * 输出："fl"
     * 示例 2:
     * 输入：strs = ["dog","racecar","car"]
     * 输出：""
     * 解释：输入不存在公共前缀。
     */

    public static String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        String minStr = Arrays.stream(strs).min(Comparator.comparing(String::length)).orElse("");
        int preLen = 0;
        boolean flag = true;
        for (int i = 0; i < minStr.length(); i++) {
            for (String str : strs) {
                if (str.charAt(preLen) != minStr.charAt(preLen)) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                preLen++;
                continue;
            }
            break;
        }
        return preLen == 0 ? "" : minStr.substring(0, preLen);
    }


    public static String longestCommonPrefix2(String[] strs) {
        if (isEmpty(strs)) {
            return "";
        }
        String minStr = Arrays.stream(strs).min(Comparator.comparing(String::length)).orElse("");
        int len = minStr.length();
        for (int i = 0; i < strs.length; i++) {
            String str = strs[i];
            if (!str.startsWith(minStr)) {
                minStr = minStr.substring(0, --len);
                i = -1;
            }
        }
        return minStr;
    }

    public static boolean isEmpty(Object object){
        if (object == null ){
            return true;
        }
        if (object instanceof Object[]){
            return ((Object[])object).length == 0;
        }
        return false;
    }

}
